const express = require('express');
const path = require('path');
const logger = require('morgan');
const bodyParser = require('body-parser');
const methodOverride = require('method-override');
const fileUpload = require('express-fileupload');
const cors = require('cors')
const http = require("http");
const {expressjwt: jwt} = require('express-jwt')
const {SECRET, ALGORITHM, EXPIRES_IN} = require('./utils/token')
// 导入路由模块
const usersRouter = require('./routes/users');
const musicRouter = require('./routes/music');
const videoRouter = require('./routes/video')
const cookieRouter = require('./routes/cookie')
const {getValueByCommandKey} = require("./utils/command");

const app = express();

// 开启jwt认证
app.use('/api',
    jwt({
        secret: SECRET,
        algorithms: [ALGORITHM],
        getToken: (req) => {
            // 从请求头获取authorization标头
            const authorization = req.headers.authorization
            if (authorization && authorization.length > 0) {
                return authorization.replace("Bearer ", "");
            }
            return null
        },
        onExpired: (req, err) => {
            // 检查是否过期
            if (Date.now() - err.inner.expiredAt.getTime() < EXPIRES_IN) {
                return;
            }
            throw err;
        }
    }).unless({
        path: [
            '/api/user/login/password', '/api/user/login/code',
            '/api/user/code/send', '/api/user/register',
            '/api/cookie/list', '/api/cookie/add', '/api/cookie/last'
        ]
    })
)
// 开启跨域
app.use(cors())
// 开启文件上传
app.use(fileUpload({
    limits: {fileSize: 50 * 1024 * 1024},
    useTempFiles: true,
    tempFileDir: '/tmp/',
    debug: true
}));
app.use(logger('dev'));
app.use(express.json());
app.use(express.urlencoded({extended: false}));
app.use(bodyParser.json());
app.use(methodOverride());
// 将静态资源暴露
app.use('/', express.static(path.join(__dirname, 'public')));


// 注册路由模块
app.use('/api/user', usersRouter);
app.use('/api/music', musicRouter)
app.use('/api/video', videoRouter)
app.use('/api/cookie', cookieRouter)

app.get('/', (req, res) => {
    res.send('Hello android backend server !')
});

// 错误处理程序
app.use(function (err, req, res, next) {
    // 处理认证异常
    if (err.name === "UnauthorizedError") {
        // err.message=invalid token
        // err.message=jwt expired
        res.status(401).json({"message": err.message})
    }
    res.status(500).json({"message": "serve error"});
});


const host = process.env.HOST || '0.0.0.0'
const port = process.env.PORT || 3900


http.createServer(app)
    .listen(port, host, () => {
        console.log(`server run http://${host}:${port}`)
    })


